<?php

namespace Frieza\Modules\Topic\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\service\wiki\AdmWiki;
use Doraemon\cache\Queue;
use Doraemon\cache\Topic\Category;
use Doraemon\model\Content\ContentCategoryLabel as mContentCategoryLabel;
use Doraemon\model\LightTopic\LightTopicInteract;
use Doraemon\model\LightTopic\LightTopicInteract as mLightTopicInteract;
use Doraemon\model\TopicActivity;
use Doraemon\model\TopTopic as mTopTopic;
use Doraemon\model\CommunityRecommendTopic as mRecommendTopic;
use Doraemon\service\admin\TopTopic as sTopTopic;
use Doraemon\service\admin\CommunityRecommendTopic as sRecommendTopic;
use Doraemon\service\admin\TopicPrize as sTopicPrize;
use Doraemon\service\Creator\UserLevel3;
use Doraemon\service\Topic\TopicActivity as sTopicActivity;
use Doraemon\service\User;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Frieza\Modules\Topic\Extensions\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Doraemon\tools\ImgUrl;
use Illuminate\Support\MessageBag;
use Doraemon\model\TopicRelation;
use Doraemon\service\Topic\TopicRemark;
use Doraemon\cache\TopicCounter;
use Doraemon\tools\Filter;
use Doraemon\model\TopicWikiRelation;
use Doraemon\model\Topic\TopicTagsRelation;
use Doraemon\model\Photos;
use Doraemon\model\Topic\TopicActivity as mTopicActivity;

class TopicNewController extends Controller
{
    const PAGE_SIZE = 20;
    const IS_RELATION_WIKI = 1;

    const CHANNEL_TAGS_FILE = '/home/adm_rsync_dir/question_hot_tags_for_search.json';
    const RECOMMEND_ANSWER_IN_ALL = "/home/adm_rsync_dir/recommend_location_topic_in_all.dic";
    const SOURCE_CATEGORY_LIST = '/admin/extend/category/child';

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params)
    {
        if (isset($params['_columns_'])) {
            unset($params['_columns_']);
        }
        if (isset($params['_pjax'])) {
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function index(Request $request, Content $content)
    {
        $request = $request->all();
        $request = self::_filterWhere($request);
        return $content
            ->header('话题管理')
            ->breadcrumb(
                ['text' => '话题列表', 'url' => '/topic/index']
            )
            ->body(self::listAction($request));
    }

    //角标设置
    public function iconChange(WorkContent $content, $id = 0)
    {
        $data = mTopicActivity::getByIdNotDel($id);
        $form = new Form($data);
        $form->radio('icon_show_type', '显示角标')
            ->options([
                mTopicActivity::ICON_SHOW_TYPE_OF_NONE => '不显示',
                mTopicActivity::ICON_SHOW_TYPE_OF_FOREVER => '显示角标',
                mTopicActivity::ICON_SHOW_TYPE_OF_TEMPORARY => '限时显示角标',
            ])
            ->when(mTopicActivity::ICON_SHOW_TYPE_OF_TEMPORARY, function (Form $form) {
                $form->datetimeRange("icon_start_time", "icon_end_time", '时间范围');
            })->when('>', mTopicActivity::ICON_SHOW_TYPE_OF_NONE, function (Form $form) {
                $form->radio('icon_type', '角标类型')
                    ->options(mTopicActivity::ICON_TYPE_DESC);
            });
        $form->hidden('id', 'id');
        $form->attribute('id', $id);
        $form->disableReset();
        $form->action('/admin/topic/new/index/seticon/');
        $form->method('POST');
        return $content->body($form);
    }

    //角标设置完成跳转js
    private function closescript()
    {
        return <<<SCRIPT
        setTimeout(function () {
              parent.window.location.reload();
        }, 1200);
SCRIPT;
    }

    public function listAction($request = [])
    {
        $isSelfAdd = 0;
        $params = (array)$request['AND'];
        $limitArr = $request['LIMIT'];

        //品类信息
        $categoryLabelAll = mContentCategoryLabel::getListFormatKey();
        $noSearch = (empty($params['id']) && empty($params['is_relation_wiki']) && empty($params['is_self_add']) && empty($params['category_first_id']) && empty($params['category_second_id']));

        //因为运营自建的但是还没有用户发布话题，所以在大数据表中搜不到，所以当但大数据表中没有时需要重新搜合并话题表
        $isTopic = 0;
        if (isset($params['title']) && !empty($params['title'])) {
            $existWhere['day'] = date('Ymd', strtotime('-1 day'));
            $existWhere['light_topic_label'] = $params['title'];
            $bigTopicExist = mLightTopicInteract::get('*', $existWhere);
            $topicExist = mTopicActivity::get('*', ['title' => $params['title']]);
            $isTopic = empty($bigTopicExist) && $topicExist;
        }

        //筛选的条件只能查合并话题表
        if ((!empty($params['id']) ||
            !empty($params['is_relation_wiki']) ||
            (isset($params['category_first_id']) && $params['category_first_id'] !== '') ||
            !empty($params['category_second_id']) || $noSearch ) &&
            (empty($params['title']) || $isTopic)
        ) {
            if (!empty($params['is_relation_wiki'])) {
                $change = [1 => 0, 2 => 1];
                $params['is_relation_wiki'] = $change[$params['is_relation_wiki']];
            }
            $topic_infos = mTopicActivity::getTopicLists($limitArr, $params);
//            //获取备注信息
//            $topicIds = array_column($topic_infos, 'id');
//            $relations = TopicRelation::getByTopicIds($topicIds);
//
//            foreach ($relations as &$relation) {
//                $relation['topic_remark'] = TopicRemark::REMARK[$relation['topic_remark_id']];
//            }
            $topicList = $topic_infos;
            $topicListAll = mTopicActivity::getTopicLists([], $params);
            $topicListAll = count($topicListAll);
        } else {
            $bigDataWhere['AND']['day'] = date('Ymd', strtotime('-1 day'));
            $bigDataWhere['LIMIT'] = $limitArr;
            if (isset($params['title']) && $params['title']) {
                $bigDataWhere['light_topic_label[~]'] = $params['title'];
            }
            if (isset($params['is_self_add']) && $params['is_self_add']) {
                $bigDataWhere['is_build_self'] = $params['is_self_add'];
            }
            $bigTopicList = mLightTopicInteract::getLightTopicInteract($bigDataWhere);
            $titlesInfo = [];
            if (!empty($bigTopicList)) {
                $titles = array_column($bigTopicList, 'light_topic_label');
                $titlesInfo = \Doraemon\service\Topic\TopicActivity::getInfoByTitles($titles);
            }

            $topicList = [];
            foreach ($bigTopicList as $val) {
                if (isset($titlesInfo[$val['light_topic_label']])) {
                    $topicList[] = $titlesInfo[$val['light_topic_label']];
                } else {
                    $topicList[] = [
                        'id' => 0,
                        'title' => $val['light_topic_label'],
                        'uid' => $val['uid'],
                        'add_uid' => $val['uid'],
                        'source' => $val['source'],
                        'admin_id' => $val['admin_id'],
                    ];
                }
            }
            unset($bigDataWhere['ORDER'], $bigDataWhere['LIMIT']);
            $topicListAll = mLightTopicInteract::getLightTopicInteractListCount($bigDataWhere);
        }
        $prizeList = sTopicPrize::getAllPrize();
        $topicTitles = array_column($topicList, 'title');
        $TopicCounter['answer'] = TopicCounter::getMultiV2($topicTitles);
        //关注数
        $topicIds = array_column($topicList, 'id');
        $TopicCounter['follow'] = TopicCounter::getMulti($topicIds);

        $gridModel = new pGridDataModel($topicList, $topicListAll, [
            'perPage' => $request['per_page'] ?: $request['LIMIT'][1],
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($prizeList, $categoryLabelAll, $isSelfAdd, $TopicCounter) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->expandFilter();

            $grid->tools(function ($tools) use ($categoryLabelAll) {
                $tools->append("<a href='awardslist' class='btn btn-sm btn-default' style='float: right;margin-left:5px;'>
<i class='fa fa-adjust'>&nbsp;&nbsp;话题广场有奖推荐管理</i></a>");
                $tools->append("<a href='communitylist' class='btn btn-sm btn-default' style='float: right;margin-left:5px;'>
<i class='fa fa-adjust'>&nbsp;&nbsp;频道首页推荐话题管理</i></a>");
                $tools->append("<a href='topanswerlist' class='btn btn-sm btn-dropbox' style='float: right;margin-left:5px;'>
<i class='fa fa-address-card'>&nbsp;&nbsp;回答固定位置管理</i></a>");
                $tools->append("<a href='new/toplist' class='btn btn-sm btn-default' style='float: right;margin-left:5px;'>
<i class='fa fa-adjust'>&nbsp;&nbsp;话题频道推荐置顶排序管理</i></a>");
                $tools->append("<a href='index/channel_info' class='btn btn-sm btn-adn' style='float: right;margin-left:5px;'>
<i class='fa fa-delicious'>&nbsp;&nbsp;编辑话题频道信息</i></a>");
            });

            $grid->filter(function (Grid\Filter $filter) use ($categoryLabelAll) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('id', 'ID')->placeholder('ID');
                    $filter->equal('title', '标题')->placeholder('标题');
                    $filter->equal('is_relation_wiki', '是否关联好物分类')->radio([
                        0 => '全部',
                        1 => '否',
                        2 => '是',
                    ]);
                    $filter->equal('is_self_add', '用户自建')->radio([
                        1 => '是',
                        2 => '否'
                    ]);
                });
                $filter->column(1 / 2, function ($filter) {
                    $categoryFirstId = request('category_first_id', null);
                    $categoryLabelSecond = [];
                    if ($categoryFirstId) {
                        $categoryLabelSecond = mContentCategoryLabel::getListFormatKey($categoryFirstId, 2);
                    }
                    $categoryLabelFirst = mContentCategoryLabel::getListFormatKey(0, 1);
                    $categoryLabelFirst[0] = '未打标签';
                    ksort($categoryLabelFirst);
                    $filter->equal('category_first_id', '一级品类')->select($categoryLabelFirst)->load('category_second_id', route('getCategoryLabel'));
                    $filter->equal('category_second_id', '二级品类')->select($categoryLabelSecond);
                });
            });

            $grid->column('id')->display(function () {
                return $this->id;
            });
            $grid->column('title', '标题')->width(150);
            $grid->column('status', '状态')->replace(mTopicActivity::STATUS)->width(50);
            $grid->column('addtime', '操作时间')->display(function () {
                return '开始时间：' . date('Y-m-d H:i:s', $this->start_time) . "<br/>添加时间：" . date('Y-m-d H:i:s', $this->addtime) . "<br/>" . '修改时间：' . date('Y-m-d H:i:s',
                        $this->edittime);
            })->width(250);

            $grid->column('admin_tag', '关联信息')
                ->display(function () use ($categoryLabelAll, $TopicCounter) {
                    $firstName = $categoryLabelAll[$this->category_first_id];
                    $secondName = $categoryLabelAll[$this->category_second_id];
                    $contentNum = $TopicCounter['answer'][$this->title]['answer'] ?? 0;
                    $followNum = $TopicCounter['follow'][$this->id]['follow'] ?? 0;
                    return "一级品类:$firstName<br/>二级品类:$secondName<br/>有效内容数:$contentNum<br/>关注数:$followNum<br/>";
                })->width(200);

            $grid->column('has_prize', '参与有奖')->display(function () use ($prizeList) {
                if (!$this->id) {
                    return '';
                }
                $status = isset($prizeList[$this->id]) ? '是' : '否';
                return "<a href='/admin/topic/{$this->id}/topicPrize' target='_blank' >$status</a>";
            });

            $grid->column('source', '创建信息')->display(function () {
                if ($this->source == mTopicActivity::SOURCE_USER_ADMIN) {
                    return isset($this->admin_id) ? Admin::user()->find($this->admin_id)->name : '';
                } else {
                    $uid = $this->add_uid;
                    if ($this->source == mTopicActivity::SOURCE_USER_FOLLOW) {
                        $uid = LightTopicInteract::get('uid', [
                            'day' => date('Ymd', strtotime('-1 day')),
                            'light_topic_label' => $this->title
                        ]);
                    }
                    $userinfo = User::getBasicUserInfoByCache($uid);
                    if (empty($userinfo)) return '';
                    $info = [
                        'uid' => "<a href='/admin/user/Detail/{$uid}' target='_blank'>{$uid}</a>",
                        '昵称' => $userinfo['nick'],
                        '生产等级' => UserLevel3::getLevelInfoByUid($uid)['user_level'] ?? '',
                    ];
                    $content = '';
                    foreach ($info as $key => $value) {
                        $content .= "<div>{$key}：{$value}</div>";
                    }
                    return $content;
                }
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->prepend('<a class="fa fa-edit" href="/admin/topic/new/' . $actions->row->id .'/edit?title='.$actions->row->title.'">编辑</a><br>');
                if (!empty($actions->row->id)) {
                    $actions->prepend('<a class="fa reload-data fa-cubes" href="/admin/topic/topictab/' . $actions->row->id . '" >话题tab管理</a><br>');
                    $actions->prepend('<a class="fa fa-indent reload-data" href="/admin/topic/topicbanner/' . $actions->row->id . '" >话题banner管理</a><br>');

                    if ($actions->row->status == 1) {
                        $actions->prepend('<a class="fa reload-data fa-level-down" href="/admin/topic/new/index/setdown/' . $actions->row->id . '" >话题下架</a><br>');
                    }
                    if ($actions->row->status == 10) {
                        $actions->prepend('<a class="fa reload-data fa-level-up" href="/admin/topic/new/index/setnormal/' . $actions->row->id . '" >话题上架</a><br>');
                    } else {
                        $id = $actions->row->id;
                        $url = "/admin/topic/new/$id/iconchange";
                        $actions->prepend('<a class="fa reload-data fa-hand-o-up btn-icon" href="javascript:var index = layer.open({
                                type: 2,
                                title: \'角标设置\',
                                maxmin: true,
                                area: [\'400px\', \'500px\'], 
                                content: \'' . $url . '\'
                                });" >角标设置</a><br/>');
                    }
                }
            });
        });

        $list = $listGrid->render();

        return $list;
    }

    //下架
    public function setDown($id)
    {
        $data = mTopicActivity::getById($id);
        if ($data) {
            $data['status'] = mTopicActivity::STATUS_ADM_DELETE;
            $data['edittime'] = time();
            $rs = sTopicActivity::save($data, $id);

            if ($rs) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                return back()->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '保存失败'
                ]);
                return back()->with(compact('error'));
            }
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    //角标设置
    public function setIcon(Request $request)
    {
        $error = new MessageBag([
            'title' => '保存失败'
        ]);
        $id = $request->post('id');
        $iconType = $request->post('icon_type');
        $iconShowType = $request->post('icon_show_type');
        $iconStartTime = $request->post('icon_start_time');
        $iconEndTime = $request->post('icon_end_time');
        $data = mTopicActivity::getByIdNotDel($id);
        if ($data) {
            $data['edittime'] = time();
            if ($iconShowType == mTopicActivity::ICON_SHOW_TYPE_OF_NONE) {
                $iconEndTime = null;
                $iconStartTime = null;
                $iconType = '';
            } elseif (!$iconType) {
                $error = new MessageBag([
                    'title' => '请设置角标类型'
                ]);
                return back()->with(compact('error'));
            }

            $data['icon_show_type'] = $iconShowType;
            $data['icon_end_time'] = $iconEndTime;
            $data['icon_start_time'] = $iconStartTime;
            $data['icon_type'] = $iconType;

            $rs = mTopicActivity::updateById($id, $data);
            if ($rs) {
                // 添加到队列，更新话题
//                Queue::insertQueue('TopicActivity/addTopicActivity', [
//                    'id' => $id,
//                ]);
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                admin_success('保存成功');
                Admin::script($this->closescript());
                return redirect('/admin/topic/new/index/closeview');
            } else {
                return back()->with(compact('error'));
            }
        } else {
            return back()->with(compact('error'));
        }
    }

    //角标设置弹框页面
    public function closeView(Request $request, Content $content)
    {
        Admin::script($this->closescript());
        return $content;
    }


    //上架
    public function setNormal($id)
    {
        $data['status'] = mTopicActivity::STATUS_SUCCESS;
        $data['edittime'] = time();

        $rs = sTopicActivity::save($data, $id);
        if ($rs) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    //添加话题页面
    public function edit(Content $content, $id = 0)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑话题';
        } else {
            $title = '添加话题';
        }
        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('话题管理')
            ->breadcrumb(
                [
                    'text' => '话题列表',
                    'url' => '/topic/index'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    //添加/修改页面
    private function editAction($id = 0)
    {
        $data = [];
        if ($id > 0) {
            //获取话题信息
            $data = mTopicActivity::get('*', ['id' => $id, 'status' => [mTopicActivity::STATUS_NORMAL, mTopicActivity::STATUS_UNTREATED]]);
            //获取额外信息
            $extra_info = TopicRelation::getByTopicId($id);
            $data['show_wiki'] = (int)$extra_info['show_wiki'] ?: 0;
            $data['top_wikis'] = (string)$extra_info['top_wikis'] ?: '';
            $data['key_words'] = (string)$extra_info['key_words'] ?: '';
            $data['topic_remark'] = $extra_info['topic_remark_id'];

            foreach (TopicRemark::REMARK_RELATION as $topicType => $topicRemarks) {
                if (in_array($extra_info['topic_remark_id'], $topicRemarks)) {
                    $data['topic_remark_type'] = $topicType;
                }
            }
            $data['color'] = '#' . $data['color'];
            if (isset($data['cron_date']) && $data['cron_date'] > time()) {
                $data['now'] = 1;
                $data['cron_date'] = date('Y-m-d', $data['cron_date']);
            }
        } else {
            $data['title'] = request('title', '');
            $data['light_topic'] = empty($data['title']) ? 0 : 1;
        }

        $form = new Form($data);
        $form->hidden('id', '话题ID');
        $form->imgUpload('cover_pic_id', '头图', true, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])
            ->help('建议尺寸：商业-750*520 社区-750*375');
        $form->imgUpload('share_pic_id', '分享图', true, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])
            ->setMinImageHeight(168)->setMaxImageHeight(168)->setMinImageWight(168)->setMaxImageWight(168)->help('请上传168（宽） x 168（高）尺寸的图片');
        $titleForm = $form->text('title', '话题标题')->required('话题标题必填')->help("只支持中英文、数字、横线、下划线,不得超过15个字");
        if ($data['title']) {
            $titleForm->readonly();
        }
        //轻话题被运营生成id
        $form->hidden('light_topic')->default($data['light_topic']);
        Admin::script($this->guideScript());
        if ($data['content']) {
            $guide = "'" . $data['content'] . "'";
            $form->html("<div id='editor' data-id={$guide} data-content={$guide}></div>");
        } else {
            $form->html("<div id='editor' data-id='' data-content=''></div>");
        }
        //品类
        $categoryLabel = mContentCategoryLabel::getListFormatKey(0, 1);
        $categoryLabelAll = mContentCategoryLabel::getListFormatKey(0, 2, 0);
        $allList = [];
        foreach ($categoryLabelAll as $info) {
            $allList[$info['p_id']][$info['id']] = $info['name'];
        }
        $categoryLabelForm = $form->select('category_first_id', '一级品类')->options($categoryLabel);
        if (!empty($data['category_first_id'])) {
            $categoryLabelForm->readOnly();
        }

        if (!empty($data['category_second_id'])) {
            $secondCategoryLabel = mContentCategoryLabel::getListFormatKey(0, 2);
            $form->select('category_second_id', '二级品类')->options($secondCategoryLabel)->readOnly();
        } else {
            foreach ($categoryLabel as $lv => $kv) {
                $categoryLabelForm->options($categoryLabel)->when($lv, function (Form $form) use ($allList, $lv, $id) {
                    $secondId = $allList[$lv] ?? [];
                    $categorySecond = $form->select('category_second_id', '二级品类')->options($secondId);
                    if (!empty($data['category_second_id'])) {
                        $categorySecond->readOnly();
                    }
                });
            }
        }
        $form->html("<span style='color: red' class='fa fa-info-circle'>提交后品类选择不可修改</span>");

        $form->color('color', '话题背景色色值');

        $form->radio('show_user', '展示发起人')->options(['1' => '展示', '0' => '不展示'])
            ->when('=', 1, function ($form) {
                $form->radio('user_type', '发起人类型')->options(['1' => '真实用户', '2' => '虚拟用户'])
                    ->when('=', 1, function ($form) {
                        $form->number('uid', '真实用户uid');
                    })->default(1)
                    ->when('=', 2, function ($form) {
                        $form->text('nick', '虚拟用户昵称');
                        $form->text('avatar', '虚拟账号头像地址');
                    });
            })->default(0);

        if ($data['status'] == mTopicActivity::STATUS_UNTREATED) {
            $form->radio('now', '定时发布')->options(['1' => '是', '0' => '否'])
                ->when('=', 1, function ($form) {
                    $form->date('cron_date', '定时发布时间');
                })->default(0);
        }

        $form->radio('show_wiki', '展示相关好物')->options(['1' => '是', '0' => '否'])
            ->when('=', 1, function ($form) {
                $form->textarea('top_wikis', '预置置顶wiki')->help('请填写wiki商品id，英文逗号分隔，最多预置5个商品');
                $form->textarea('key_words', 'wiki关键词配置')->help('请填写wiki关键词，英文逗号分隔，最多设置8个关键词');
            })->default(0);


        $form->imgUpload('button_pic_id', '参与话题按钮图', true, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])->help('未上传使用默认参与按钮');

        $form->radio('topic_remark_type', '话题备注类型')->options(TopicRemark::REMARK_TYPE)
            ->when(TopicRemark::REMARK_TYPE_SALE, function ($form) {
                $form->radio('topic_remark', '话题备注')->options(TopicRemark::REMARK_SALE);
            })
            ->when(TopicRemark::REMARK_TYPE_CONTENT, function ($form) {
                $form->radio('topic_remark', '话题备注')->options(TopicRemark::REMARK_CONTENT);
            })
            ->when(TopicRemark::REMARK_TYPE_TOPIC, function ($form) {
                $form->radio('topic_remark', '话题备注')->options(TopicRemark::REMARK_TOPIC);
            })
            ->when(TopicRemark::REMARK_TYPE_OPERATION, function ($form) {
                $form->radio('topic_remark', '话题备注')->options(TopicRemark::REMARK_OPERATION);
            });

        $form->radio('is_relation_wiki', '是否是好物相关话题')->options(['1' => '是', '0' => '否'])
            ->when(TopicRemark::REMARK_TYPE_SALE, function ($form) use ($id) {
                //获取已经关联的wiki
                $wikis = TopicWikiRelation::getWikiByTopicId($id);
                $categoryId = array_column($wikis, 'category_id', 'category_level');
                $topCategory = AdmWiki::admGetChildCategoryMap(0);
                $form->select('category_id', '好物分类')->options($topCategory)->load('second_category_id', self::SOURCE_CATEGORY_LIST)->default($categoryId[1]);
                $secondCategory = AdmWiki::admGetChildCategoryMap($categoryId[1]);
                $form->select('second_category_id', '好物二级分类')->options($secondCategory)->default($categoryId[2]);
            })->default(0);

        $form->radio('sort_type', '默认瀑布流')->options(['1' => '热门', '2' => '最新']);
        $form->action('/admin/topic/new/save');
        // 去掉原有的重置提交按钮
        $form->disableSubmit();
        $form->disableReset();
        Admin::script($this->getGuideScript());
        $form->hidden('content', '轻话题引导语');
        $form->html('<div style="text-align:center;padding-top: 40px" >
            <input class="btn btn-sm btn-info button-1134271147" type="submit" id="light_topic_save" value="提交" style="margin-left: 500px;width: 100px;height: 40px"></div> ');

        return $form;
    }

    function getChinaEnglishNumStrlen($str)
    {
        return preg_match("/^[\x{4e00}-\x{9fa5}0-9a-zA-Z_-]+$/u", $str);
    }

    //话题保存
    public function submitTopic(Request $request)
    {
        $request = $request->all();
        $request['admin_id'] = Admin::user()->id;
        $request['start_time'] = strtotime($request['cron_date']) ?: time();
        $request['status'] = $request['start_time'] <= time() ? 1 : 0;
        $request['color'] = str_replace('#', '', $request['color']);
        $request['is_forever'] = 1;
        $request['cron_date'] = strtotime($request['cron_date']);
        $request['title'] = trim($request['title']);
        $extra['show_wiki'] = (int)$request['show_wiki'];
        $extra['topic_remark_id'] = (int)$request['topic_remark'];
        $extra['top_wikis'] = implode(',', array_slice(array_unique(explode(',', $request['top_wikis'])), 0, 5));
        $extra['key_words'] = implode(',', array_slice(array_unique(explode(',', $request['key_words'])), 0, 8));
        $wikiRelation['category_id'] = $request['category_id'];
        $wikiRelation['second_category_id'] = $request['second_category_id'];
        if (mb_strlen($request['title']) > 15 || !$this->getChinaEnglishNumStrlen($request['title'])) {
            throw new InputErrorException('请按照规则创建话题名称', InputErrorException::DEFAULT_CODE, 'title');
        }
        if ($request['category_first_id'] && empty($request['category_second_id'])) {
            throw new InputErrorException('请选择二级品类', InputErrorException::DEFAULT_CODE, 'category_second_id');
        }
        $lightTopic = $request['light_topic'];
        unset($request['light_topic']);
        unset($request['key_words']);
        unset($request['show_wiki']);
        unset($request['top_wikis']);
        unset($request['topic_remark_type']);
        unset($request['topic_remark']);
        unset($request['_token']);
        unset($request['now']);
        unset($request['category_id']);
        unset($request['second_category_id']);
        unset($request['tags']);
        if (isset($request['id']) && $request['id']) {
            //修改
            $request['edittime'] = time();
            $result = sTopicActivity::save($request, $request['id']);

            $extra_info = TopicRelation::getByTopicId($request['id']);
            $extra['admin_id'] = Admin::user()->id;
            $extra['topic_activity_id'] = $request['id'];
            if ($extra_info && is_array($extra_info)) {
                $extra['edittime'] = date('Y-m-d H:i:s', time());
                TopicRelation::editData($extra, $request['id']);
            } else {
                $extra['addtime'] = date('Y-m-d H:i:s', time());
                TopicRelation::addData($extra);
            }

            if ($request['is_relation_wiki'] == self::IS_RELATION_WIKI) {
                $res1 = TopicWikiRelation::updateByTopicId($request['id'], 1, [
                    'category_id' => $wikiRelation['category_id'],
                    'update_time' => time(),
                ]);

                $res2 = TopicWikiRelation::updateByTopicId($request['id'], 2, [
                    'category_id' => $wikiRelation['second_category_id'],
                    'update_time' => time(),
                ]);

                if (!$res1 && !$res2) {
                    $this->addTopicWikiRelation($request['id'], $wikiRelation);
                }
            }
        } else {
            //查询表里是都有名称
            $exits = mTopicActivity::getDetailByKeyword($request['title']);
            if (!empty($exits)) {
                $error = new MessageBag([
                    'title' => '保存失败,系统已有该话题'
                ]);
                return back()->with(compact('error'));
            }
            //添加
            $request['addtime'] = time();
            //创建添加运营来源
            $request['source'] = mTopicActivity::SOURCE_USER_ADMIN;
            if ($lightTopic) {//用户自建,查询大数据表获取自建用户信息
                $lightInfo = LightTopicInteract::get('*', [
                    'day' => date('Ymd', strtotime('-1 day')),
                    'light_topic_label' => $request['title']
                ]);
                if (!empty($lightInfo)) {
                    $request['source'] = $lightInfo['is_build_self'] ?: mTopicActivity::SOURCE_USER_ADD;
                    $request['add_uid'] = $lightInfo['uid'];
                }
            }
            $result = sTopicActivity::save($request);
            $extra['addtime'] = date('Y-m-d H:i:s', time());
            TopicRelation::addData($extra);
            //选择关联后，创建话题与wiki的关联
            if ($request['is_relation_wiki'] == self::IS_RELATION_WIKI) {
                $rowCount = $this->addTopicWikiRelation($result, $wikiRelation);
                if ($rowCount <= 0) {
                    Log::error('关联好物失败，影响行数 => ', $rowCount);
                }
            }
        }

        if ($result) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/topic/new')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    private function addTopicWikiRelation($topicId, $wikiRelation)
    {
        return TopicWikiRelation::add([
            [
                'topic_id' => $topicId,
                'category_id' => $wikiRelation['category_id'],
                'category_level' => 1,
                'create_time' => time(),
                'update_time' => time(),
            ],
            [
                'topic_id' => $topicId,
                'category_id' => $wikiRelation['second_category_id'],
                'category_level' => 2,
                'create_time' => time(),
                'update_time' => time(),
            ]
        ]);
    }

    //话题频道信息
    public function channelInfo(Request $request, Content $content)
    {
        $tab = new Tab();

        $tab->add("话题频道管理", $this->editChannelAction());
        return $content
            ->header('话题管理')
            ->breadcrumb(
                [
                    'text' => '话题列表',
                    'url' => '/topic/new'
                ],
                ['text' => "话题频道管理"]
            )
            ->body($tab);
    }

    public function editChannelAction()
    {
        $channel_tags = '';
        if (file_exists(self::CHANNEL_TAGS_FILE)) {
            $channel_tags = json_decode(file_get_contents(self::CHANNEL_TAGS_FILE), true);
            if ($channel_tags && is_array($channel_tags)) {
                $channel_tags = implode(',', $channel_tags);
            }
        }

        $form = new Form(['channel_tags' => $channel_tags]);
        $form->textarea('channel_tags', '频道类别')->required('频道类别不可为空')->help('英文逗号分隔');

        $form->action('/admin/topic/index/channel_info/save');

        return $form;
    }

    //保存频道列表
    public function saveChannelInfo(Request $request)
    {
        $request = $request->all();
        $channel_tags = $request['channel_tags'];
        $channel_tags_arr = explode(',', $channel_tags);

        $res = Category::setCategory($channel_tags_arr);
        if ($res) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    /**
     * 回答固定位置页面
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function topAnswerList(Request $request, Content $content)
    {
        if (file_exists(self::RECOMMEND_ANSWER_IN_ALL)) {
            $answers = file_get_contents(self::RECOMMEND_ANSWER_IN_ALL);
            $form = new Form(['text' => $answers]);
            $form->textarea('text', '回答固定位置')->rows(20)->help('填写话题id，回答id和位置，以|分隔，一行一个');
            $form->action('/admin/topic/topanswer/save');
            return $content
                ->header('回答固定位置管理')
                ->breadcrumb(
                    [
                        'text' => '话题列表',
                        'url' => '/topic/index'
                    ],
                    ['text' => "回答固定位置管理"]
                )
                ->body($form);
        } else {
            return $content
                ->header('回答固定位置管理')
                ->breadcrumb(
                    [
                        'text' => '话题列表',
                        'url' => '/topic/index'
                    ],
                    ['text' => "回答固定位置管理"]
                )
                ->body([]);
        }
    }


    //根据一级品类获取二级、筛选联动
    public function getCategoryLabel()
    {
        $pid = \request()->get('q', 0);
        $data = mContentCategoryLabel::getListFormatKey($pid);
        $result = [];
        foreach ($data as $key => $val) {
            $result[] = [
                'id' => $key,
                'text' => $val,
            ];
        }
        return $result;
    }

    /**
     * 回答固定位置保存
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function topAnswerSave(Request $request)
    {
        $request = $request->all();
        $answers = $request['text'];
        $list = explode(PHP_EOL, $answers);
        if ($list) {
            $idList = array_map(function ($data) {
                return explode('|', $data)[1];
            }, $list);
            $hasDown = Photos::select('id', ['id' => $idList, 'is_bottom' => Photos::IS_BOTTOM_YES]);
            if ($hasDown) {
                $ids = rtrim(join(',', $hasDown), ',');
                throw new InputErrorException('提交失败！内容' . $ids . '已被置底，不可添加固定位', InputErrorException::DEFAULT_CODE, 'text');
            }
        }
        if (file_exists(self::RECOMMEND_ANSWER_IN_ALL)) {
            file_put_contents(self::RECOMMEND_ANSWER_IN_ALL, $answers);
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return back()->with(compact('success'));
        }
        $error = new MessageBag([
            'title' => '保存失败'
        ]);
        return back()->with(compact('error'));
    }

    private function guideScript()
    {
        return <<<SCRIPT
function loadScript(src, callback) {
var script = document.createElement("script");

if(script.addEventListener)
script.addEventListener("load", callback, false);
else if(script.attachEvent)
script.attachEvent("onreadystatechange",
function() { loadScript.callbackIE(callback); });

script.src = src;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript.callbackIE = function(callback) {
var target = window.event.srcElement;
if(target.readyState == "loaded")
callback.call(target);
};

// load 30k script.
// Listener.cleanUp is defined at the bottom of drag.js
callback = function() {

editor.init({
            selectRequestUrl: '/api/link/linkmodule',
            submitRequestUrl: '/api/link/linkformat',
            rootNodeId: 'editor'
        });
};

loadScript("/vendor/js/frieza-fe/editor.js", callback);
SCRIPT;
    }

    private function getGuideScript()
    {
        return <<<SCRIPT
          $('#light_topic_save').unbind('click').click(function(){
            var data = document.getElementById('editor').getAttribute('data-content');
            $(".content").attr("value",data);
          });
SCRIPT;
    }
    /**
     * 话题频道推荐置顶列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function topList(Request $request, Content $content)
    {
        $limit = [];
        $isOver = $request->input('is_over',0);
        if($isOver){
            $page = $request->input('page', 1);
            $pageSize = $request->input('per_page', 50);
            $limit = [($page - 1) * $pageSize, $pageSize];
        }
        $list = sTopTopic::getTopListAllNew($limit);
        if(isset($list['list']) && is_array($list['list']) && $list['list']) {
            $topicIds = array_column($list['list'], 'topic_id');
            $topicInfos = mTopicActivity::getByIdsNotDel($topicIds);
            $topicArrs = [];
            if($topicInfos && is_array($topicInfos)) {
                foreach($topicInfos as $topicInfo) {
                    $topicArrs[$topicInfo['id']] = $topicInfo;
                }
            }
            foreach($list['list'] as &$topInfo) {
                $topInfo['title'] = $topicArrs[$topInfo['topic_id']]['title'];
            }
        }

        $gridModel = new pGridDataModel($list['list'], $list['total']);
        $grid = Admin::grid($gridModel, function (Grid $grid)use($isOver) {
                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/topic/0/topTopic/create" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
                });
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->equal('is_over', '是否结束')->checkbox([1 => '是']);
                });
                $grid->disableExport();
                $grid->disableRowSelector();
//                $grid->disableFilter();
                if(!$isOver){
                    $grid->disablePagination();
                }
//                $grid->disableActions();
                $grid->disableCreateButton();
                $grid->perPages([50]);
                $grid->column('id', '话题置顶id')->sort();
                $grid->column('topic_id', '话题id');
                $grid->column('title', '话题标题');
                $grid->column('start_time', '开始时间');
                $grid->column('end_time', '结束时间');
                $grid->column('top_sttaus', '展示状态')->display(function () {
                    if($this->start_time < date('Y-m-d H:i:s') && $this->end_time > date('Y-m-d H:i:s')) {
                        $showStatus = '进行中';
                    } else if ($this->end_time < date('Y-m-d H:i:s')) {
                        $showStatus = '已结束';
                    } else {
                        $showStatus = '未开始';
                    }
                    return $showStatus;
                });
                $grid->column('user_profile', '分群信息')->userProfile();
                $grid->column('admin_id', '创建者')->display(function () {
                    return Admin::user()->find($this->admin_id)->name;
                });
                $grid->actions(function (Grid\Displayers\Actions $actions){
                    $actions->disableView();
                    $actions->disableEdit();
                    $actions->prepend('<a class="fa fa-edit" href="/admin/topic/0/topTopic/'.$actions->row->id.'/edit">编辑</a><br>');
                });
            }
        );
        return $content->header('话题置顶列表')
            ->breadcrumb(['text' => '话题列表', 'url' => '/topic/new'], ['text' => '话题置顶列表'])
            ->row($grid);
    }

    public function deleteTop($id)
    {
        $id = sTopTopic::delete($id, Admin::user()->id);
        if ($id) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => '删除失败',
            ]);
        }
    }

    /**
     * 社区频道话题列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function communityList(Request $request, Content $content)
    {
        $limit = [];
        $isOver = $request->input('is_over',0);
        if($isOver){
            $page = $request->input('page', 1);
            $pageSize = $request->input('per_page', 50);
            $limit = [($page - 1) * $pageSize, $pageSize];
        }
        $list = sRecommendTopic::getRecommendListAllNew($limit);
        if(isset($list['list']) && is_array($list['list']) && $list['list']) {
            $topicIds = array_column($list['list'], 'topic_id');
            $topicInfos = mTopicActivity::getByIdsNotDel($topicIds);
            $topicArrs = [];
            if($topicInfos && is_array($topicInfos)) {
                foreach($topicInfos as $topicInfo) {
                    $topicArrs[$topicInfo['id']] = $topicInfo;
                }
            }
            foreach($list['list'] as &$topInfo) {
                $topInfo['title'] = $topicArrs[$topInfo['topic_id']]['title'];
            }
        }

        $gridModel = new pGridDataModel($list['list'], $list['total']);
        $grid = Admin::grid($gridModel, function (Grid $grid)use($isOver) {
            $grid->tools(function (Grid\Tools $tool) {
                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/topic/recommendtopic/create" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->equal('is_over', '是否结束')->checkbox([1 => '是']);
            });
            $grid->disableExport();
            $grid->disableRowSelector();
//                $grid->disableFilter();
            if(!$isOver){
                $grid->disablePagination();
            }
//                $grid->disableActions();
            $grid->disableCreateButton();
            $grid->perPages([50]);
            $grid->column('id', '话题推荐id')->sort("communitylist/sort");
            $grid->column('topic_id', '话题id');
            $grid->column('title', '话题标题');
            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('status', '展示状态')->display(function () {
                if($this->start_time < date('Y-m-d H:i:s') && $this->end_time > date('Y-m-d H:i:s')) {
                    $showStatus = '进行中';
                } else if ($this->end_time < date('Y-m-d H:i:s')) {
                    $showStatus = '已结束';
                } else {
                    $showStatus = '未开始';
                }
                return $showStatus;
            });
            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->column('admin_id', '创建者')->display(function () {
                return Admin::user()->find($this->admin_id)->name;
            });
            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();
                $actions->disableEdit();
                $actions->prepend('<a class="fa fa-edit" href="/admin/topic/recommendtopic/'.$actions->row->id.'/edit">编辑</a><br>');
            });
        }
        );
        return $content->header('话题推荐列表')
            ->breadcrumb(['text' => '话题列表', 'url' => '/topic/new'], ['text' => '话题推荐列表'])
            ->row($grid);
    }

    public function recommendTopicCreate(Content $content, $id = 0)
    {
        $where = ['status[!]' => mTopicActivity::STATUS_DELETE];
        $topicAll = mTopicActivity::select(['id', 'title'], $where);
        $topicList = [];
        foreach ($topicAll as $val) {
            $topicList[$val['id']] = $val['title'];
        }

        $info = [];
        if ($id) {
            $info = sRecommendTopic::getInfo($id);
        }
        $form = new \Encore\Admin\Widgets\Form($info);
        $form->hidden('id', 'id');
        $form->select('topic_id', '话题')->options($topicList)->required();
        $form->datetimeRange('start_time', 'end_time', '推荐时间')->attribute('autocomplete', 'off')->required();
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->action("/admin/topic/recommendtopic/save");

        return $content->header('频道推荐话题列表编辑')
            ->breadcrumb(
                ['text' => '话题列表', 'url' => '/topic/new'],
                ['text' => '话题置顶列表', 'url' => "topic/communitylist"],
                ['text' => '频道推荐话题列表编辑']
            )->body($form);
    }

    public function recommendTopicSave(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $topicId = $request->input('topic_id');

            $data = [
                'topic_id' => $topicId,
                'start_time' => $request->input('start_time', ''),
                'end_time' => $request->input('end_time', ''),
                'type' => 1,
                'admin_id' => Admin::user()->id,
                'status' => mRecommendTopic::STATUS_NORMAL
            ];

            if ($data['start_time'] == $data['end_time']) {
                throw new \Exception('置顶时间不能相等');
            }

            $id = sRecommendTopic::save($id, $data, $request->input('user_profile'));

            if ($id) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                return redirect(url("/admin/topic/communitylist"))->with(compact('success'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function deleteRecommend($id)
    {
        $id = sRecommendTopic::delete($id, Admin::user()->id);
        if ($id) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => '删除失败',
            ]);
        }
    }

    /**
     * 社区频道推荐排序
     * @param Request $request
     */
    public function sortRecommend(Request $request)
    {
        $request = $request->all();
        $sortArr = $request['sort'];
        if($sortArr && is_array($sortArr)) {
            foreach($sortArr as $id => $sort) {
                mRecommendTopic::save($id, [
                    'edit_time' => date('Y-m-d H:i:s', time()),
                    'sort' => (int) $sort
                ]);
            }
        }
    }


    /**
     * 有奖tab话题列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function awardsList(Request $request, Content $content)
    {
        $limit = [];
        $isOver = $request->input('is_over',0);
        if($isOver){
            $page = $request->input('page', 1);
            $pageSize = $request->input('per_page', 50);
            $limit = [($page - 1) * $pageSize, $pageSize];
        }
        $list = sRecommendTopic::getRecommendListAllNew($limit, 2);

        if(isset($list['list']) && is_array($list['list']) && $list['list']) {
            $topicIds = array_column($list['list'], 'topic_id');
            $topicInfos = mTopicActivity::getByIdsNotDel($topicIds);
            $topicArrs = [];
            if($topicInfos && is_array($topicInfos)) {
                foreach($topicInfos as $topicInfo) {
                    $topicArrs[$topicInfo['id']] = $topicInfo;
                }
            }
            foreach($list['list'] as &$topInfo) {
                $topInfo['title'] = $topicArrs[$topInfo['topic_id']]['title'];
            }
        }

        $gridModel = new pGridDataModel($list['list'], $list['total']);
        $grid = Admin::grid($gridModel, function (Grid $grid)use($isOver) {
            $grid->tools(function (Grid\Tools $tool) {
                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/topic/awardstopic/create" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->equal('is_over', '是否结束')->checkbox([1 => '是']);
            });
            $grid->disableExport();
            $grid->disableRowSelector();
//                $grid->disableFilter();
            if(!$isOver){
                $grid->disablePagination();
            }
//                $grid->disableActions();
            $grid->disableCreateButton();
            $grid->perPages([50]);
            $grid->column('id', '话题推荐id')->sort("awardslist/sort");
            $grid->column('topic_id', '话题id');
            $grid->column('title', '话题标题');
            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('status', '展示状态')->display(function () {
                if($this->start_time < date('Y-m-d H:i:s') && $this->end_time > date('Y-m-d H:i:s')) {
                    $showStatus = '进行中';
                } else if ($this->end_time < date('Y-m-d H:i:s')) {
                    $showStatus = '已结束';
                } else {
                    $showStatus = '未开始';
                }
                return $showStatus;
            });
            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->column('admin_id', '创建者')->display(function () {
                return Admin::user()->find($this->admin_id)->name;
            });
            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();
                $actions->disableEdit();
                $actions->prepend('<a class="fa fa-edit" href="/admin/topic/awardstopic/'.$actions->row->id.'/edit">编辑</a><br>');
            });
        }
        );
        return $content->header('有奖推荐话题列表')
            ->breadcrumb(['text' => '话题列表', 'url' => '/topic/new'], ['text' => '有奖推荐话题列表'])
            ->row($grid);
    }

    /**
     * 有奖tab新增/编辑
     * @param Content $content
     * @param $id
     * @return Content
     */
    public function awardsTopicCreate(Content $content, $id = 0)
    {
        $where = ['status[!]' => mTopicActivity::STATUS_DELETE];

        $topicAll = mTopicActivity::select(['id', 'title'], $where);
        $topicList = [];
        foreach ($topicAll as $val) {
            $topicList[$val['id']] = $val['title'];
        }

        $info = [];
        if ($id) {
            $info = sRecommendTopic::getInfo($id, 2);
        }
        $form = new \Encore\Admin\Widgets\Form($info);
        $form->hidden('id', 'id');
        $form->select('topic_id', '话题')->options($topicList)->required();
        $form->datetimeRange('start_time', 'end_time', '推荐时间')->attribute('autocomplete', 'off')->required();
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->action("/admin/topic/awardstopic/save");

        return $content->header('有奖推荐话题列表编辑')
            ->breadcrumb(
                ['text' => '话题列表', 'url' => '/topic/new'],
                ['text' => '有奖推荐话题列表', 'url' => "topic/awardslist"],
                ['text' => '有奖推荐话题列表编辑']
            )->body($form);
    }

    /**
     * 有奖tab保存
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void|null
     */
    public function awardsTopicSave(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $topicId = $request->input('topic_id');

            $data = [
                'topic_id' => $topicId,
                'start_time' => $request->input('start_time', ''),
                'end_time' => $request->input('end_time', ''),
                'type' => 2,
                'admin_id' => Admin::user()->id,
                'status' => mRecommendTopic::STATUS_NORMAL
            ];

            if ($data['start_time'] == $data['end_time']) {
                throw new \Exception('置顶时间不能相等');
            }

            $id = sRecommendTopic::save($id, $data, $request->input('user_profile'));

            if ($id) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                return redirect(url("/admin/topic/awardslist"))->with(compact('success'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function deleteAwards($id)
    {
        $id = sRecommendTopic::delete($id, Admin::user()->id);
        if ($id) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => '删除失败',
            ]);
        }
    }

    /**
     * 有奖tab话题排序
     * @param Request $request
     */
    public function sortAwards(Request $request)
    {
        $request = $request->all();
        $sortArr = $request['sort'];
        if($sortArr && is_array($sortArr)) {
            foreach($sortArr as $id => $sort) {
                mRecommendTopic::save($id, [
                    'edit_time' => date('Y-m-d H:i:s', time()),
                    'sort' => (int) $sort
                ]);
            }
        }
    }
}
